<?php

namespace app\api\controller;

use app\api\controller\Tpmecmscom;
use think\Db;
use think\Session;
use EasyWeChat\Factory;
use think\Config;
use fast\Http;

/**
 * 模版消息
 */
class Template extends Tpmecmscom
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    // public function _initialize()
    // {
    //     parent::_initialize();
    //     // $uid = $this->request->param('uid');//用户uid 需要解密
    //     // if(!empty($uid))$this->uid_de($uid);
    // }



    /**
     * 更新微信公众号wx_openid
     *
     * @return void
     */
    public function update_wx_openid()
    {
        $app = $this->get_wx_gzh_app();
        $next_openid = null;//'oYBUWs3A4KD6kfvfBXXcJOor9-Tw';
        $ci = 0;
        // halt($users);
        // $t= true;
     
            $users = $app->user->list($next_openid);
            // if($users['total']<130 || empty($users)){$t =false;}
            // $next_openid = $users['next_openid'];
        // halt($users);
            foreach($users['data']['openid'] as $key=>$openId){
                $wx_data = Db::name('user')->where('wx_openid',$openId)->find();
                unset($up_data);
                if(!$wx_data){//没有微信公众号的opengid  才去执行

                    $user = $app->user->get($openId);
                    // print_r($users);
                    // halt($user);
                    // if(!empty($user['openid']) && !empty($user['unionid'])){
                        $up_data['wx_openid'] = $user['openid'];//微信openid
                        $up_data['nickname'] = $user['nickname'];//微信nickname
                        $up_data['avatar']  = $user['headimgurl'];//微信headimgurl
                        $t_user = Db::name('user')->where('unionid',$user['unionid'])->find();
                        if($t_user){
                            // halt($t_user);

                            $res = Db::name('user')->where('unionid',$user['unionid'])->update($up_data);
                            if($res){
                                $ci++;
                            }

                        }
                        
                        unset($up_data);
                        
                    // }
                    unset($user);
                }else{
                    $user = $app->user->get($openId);
                    
                    $up_data['nickname'] = $user['nickname'];//微信nickname
                    $up_data['avatar']  = $user['headimgurl'];//微信headimgurl
                    $up_data['updatetime']  = time();
                    Db::name('user')->where('wx_openid',$openId)->update($up_data);
                }
                
            }
      
        echo $ci;
        file_put_contents('./gz_all.txt',$users['total']);
        // halt($users);
    }



    public function update_wx_openid_new($unionid)
    {
        $app = $this->get_wx_gzh_app();
        $next_openid = null;//'oYBUWs3A4KD6kfvfBXXcJOor9-Tw';
        $ci = 0;
        // halt($users);
        // $t= true;
     
            $users = $app->user->list($next_openid);
            // if($users['total']<130 || empty($users)){$t =false;}
            // $next_openid = $users['next_openid'];
        // halt($users);
            foreach($users['data']['openid'] as $key=>$openId){
                $wx_data = Db::name('user')->where('wx_openid',$openId)->find();
                if(!$wx_data){//没有微信公众号的opengid  才去执行

                        $user = $app->user->get($openId);
                        // print_r($users);
                        // halt($user);
                        // if(!empty($user['openid']) && !empty($user['unionid'])){
                            $up_data['wx_openid'] = $user['openid'];//微信openid
                            $up_data['nickname'] = $user['nickname'];//微信nickname
                            $up_data['headurl']  = $user['headimgurl'];//微信headimgurl
                            $t_user = Db::name('user')->where('unionid',$user['unionid'])->find();
                            if($t_user){
                                // halt($t_user);

                                $res = Db::name('user')->where('unionid',$user['unionid'])->update($up_data);
                                if($res){
                                    $ci++;
                                }

                            }
                           
                            unset($up_data);
                            
                        // }
                        unset($user);
                    }
                
            }
      
        echo $ci;
        file_put_contents('./gz_all.txt',$users['total']);
        // halt($users);
    }






    // //获取商户的全部uid
    // public function get_all_ltd_uid($goods_ids=null){
    //     if($goods_ids){
    //         //如果是多个
           
    //         $goods_ids = explode(',',$goods_ids);
    //         $uids = array();
    //         foreach($goods_ids as $key=>$goods_id){
    //             $where[] = ['exp',Db::raw("FIND_IN_SET($goods_id,goods_ids)")];
    //             $uid_temp = Db::name('ltd')
    //                 ->where('siteswitch',1)
    //                 ->where($where)//多可能不对  要goods_ids里面其中一个  此商户包含
    //                 ->column('uid');
    //             if($uid_temp){
    //                 foreach ($uid_temp as $key => $uid) {
    //                     if(!empty($uid)){
    //                         if(!in_array($uid,$uids)){
    //                             $uids[] = $uid;
    //                         }
                            
    //                     }
    //                 }
                    
    //             }
    //         }

            
    //     }else{
    //         $uids = Db::name('ltd')->where('siteswitch',1)->where('uid','>',0)->column('uid');
    //     }



        
    //     return $uids;
    // }

    // //获取商户的微信公众号openid
    // public function get_ltd_wx_openid($id){
    //     $uid = Db::name('ltd')->where('id',$id)->value('uid');
    //     if($uid){
    //         return Db::name('user')->where('id',$uid)->value('wx_openid');
    //     }else{
    //         return null;
    //     }        
    // }








































//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2021/07/17
//      |_|                                         | TpMeCMS   模板消息开始






    /**
     * 发送私人定制给——公众号模板消息给后台所有人员
     * @ApiInternal()
     * @param string $wx_openid 微信公众号openid
     * @param string $keyword1 自定义
     * @param string $keyword2 自定义
     * @param string $path
     * @return void
     */
    public function send_need_template_message_admin($need_id)
    {
        $user_ids = Db::name('admin')->where('user_id','>',0)->column('user_id');
        $wx_openids = Db::name('user')->where('id','in',$user_ids)->where('wx_openid','NOT',null)->column('wx_openid');
        if($wx_openids){
            foreach($wx_openids as $val){
                $this->send_need_template_message_admin_run($val);
            }
        }
    }


    /**
     * 发送私人定制给——公众号模板消息
     * @ApiInternal()
     * @param string $wx_openid 微信公众号openid
     * @return void
     */
    protected function send_need_template_message_admin_run($wx_openid)
    {
  
        $app = $this->get_wx_gzh_app();    
       
        // $data = $app->template_message->send([
        //     'touser' => $wx_openid,//微信公众号openid,
        //     'template_id' => 'BTt8InLySnbzZTz3PcWrkom39cLrQtC_HW-yXE4JjzI',//模板消息id 新订单待处理通知
        //     'url' => 'https://he4966.cn/',//模板消息跳转地址
        //     // 'miniprogram' => [              //模板消息跳转小程序。小程序比网址优先级高，也可以注释其一
        //     //         'appid' => Config('site.app_id'),
        //     //         'pagepath' => $path,
        //     // ],
        //     'data' => [
        //         'first' =>['您好，您有新的订单信息，请及时查看','#173177'],
        //         'keynote1' =>[$keyword1,'#173177'],//对方微信昵称
        //         'keynote2' =>[$keyword2,'#173177'],//订单时间
        //         'keynote3' =>[$service,'#173177'],//房屋名称：
        //         'remark' =>['请尽快登入小程序查看','#173177'],

        //     ],
        // ]);
        // halt($data);
        // return $data;
    }



    /**
     * 发送给用户需要支付信息
     * @ApiInternal()
     * @param id $order_id 订单id
     * @param string $path
     * @return void
     */
    public function send_order_need_pay_msg($order_id)
    {
        $order = Db::name('order')->find($order_id);
        
        $app = $this->get_wx_gzh_app();    

        $wx_openid = Db::name('user')->where('id',$order['uid'])->value('wx_openid');
        try {
            $data = $app->template_message->send([
                'touser' => $wx_openid,//微信公众号openid,
                'template_id' => '6UmM1sOq1gprlTt4k6gZD2AxJGdCGOXxFcKonRGpMl4',//模板消息id 	订单提交成功通知
                'url' => 'https://he4966.cn/',//模板消息跳转地址
                // 'miniprogram' => [              //模板消息跳转小程序。小程序比网址优先级高，也可以注释其一
                //         'appid' => Config('site.app_id'),
                //         'pagepath' => $path,
                // ],
                'data' => [
                    'first' =>['您好，有订单需要支付，请及时处理','#173177'],
                    'keyword1' =>[$order['name'],'#173177'],//用户名
                    'keyword2' =>[$order_id,'#173177'],//订单号
                    'keyword3' =>[date('Y-m-d H:i:s'),'#173177'],//下单时间：
                    'remark' =>['请到小程序上查看','#173177'],
    
                ],
            ]);
        } catch (\Throwable $th) {
            $this->success('对方没有关注公众或其他原因,发送模版消息失败');
        }

      
        
        
    }




    /**
     * 发送订单支付信息   
     * @ApiInternal()
     * @param id $order_id 订单id
     * @param string $keyword1 自定义
     * @param string $keyword2 自定义
     * @param string $path
     * @return void
     */
    public function send_order_pay_msg($order_id)
    {
        $order = Db::name('order')->find($order_id);

        $app = $this->get_wx_gzh_app();    
        foreach($this->GetWeiXinMsgOpenids() as $wx_openid){

            try {
                $data = $app->template_message->send([
                    'touser' => $wx_openid,//微信公众号openid,
                    'template_id' => 'w-B_xGPx9dBYmQIDqLTSIhZlMHzNUDqjWcCdfwLfrvY',//模板消息id 定金支付通知
                    'url' => 'https://he4966.cn/',//模板消息跳转地址
                    // 'miniprogram' => [              //模板消息跳转小程序。小程序比网址优先级高，也可以注释其一
                    //         'appid' => Config('site.app_id'),
                    //         'pagepath' => $path,
                    // ],
                    'data' => [
                        'first' =>['您好，订单支付通知，请及时查看','#173177'],
                        'keyword1' =>[$order_id,'#173177'],//订单编号
                        'keyword2' =>[$order['price'],'#173177'],//支付金额
                        'keyword3' =>[date('Y-m-d H:i'),'#173177'],//支付时间：
                        'remark' =>['请到后台查看','#173177'],
        
                    ],
                ]);
            } catch (\Throwable $th) {
                
            }
        }
        
       
        // halt($data);
        // return $data;
    }



    /**
     * 发送用户下单信息
     * 
     * @param id $order_id 订单id
     * @param string $keyword1 自定义
     * @param string $keyword2 自定义
     * @param string $path
     * @return void
     */
    public function send_user_create_order_msg($order_id)
    {
        $order = Db::name('order')->find($order_id);
        
        $app = $this->get_wx_gzh_app();    
        // if($order['pid']){
            
        // }
        foreach($this->GetWeiXinMsgOpenids() as $wx_openid){

            try {
                $data = $app->template_message->send([
                    'touser' => $wx_openid,//微信公众号openid,
                    'template_id' => '6UmM1sOq1gprlTt4k6gZD2AxJGdCGOXxFcKonRGpMl4',//模板消息id 	订单提交成功通知
                    'url' => 'https://he4966.cn/',//模板消息跳转地址
                    // 'miniprogram' => [              //模板消息跳转小程序。小程序比网址优先级高，也可以注释其一
                    //         'appid' => Config('site.app_id'),
                    //         'pagepath' => $path,
                    // ],
                    'data' => [
                        'first' =>['您好，有用户下订单'.$order_id.'请及时查看','#173177'],
                        'keyword1' =>[$order['name'],'#173177'],//用户名
                        'keyword2' =>[$order_id,'#173177'],//订单号
                        'keyword3' =>[date('Y-m-d H:i:s'),'#173177'],//下单时间：
                        'remark' =>['请到后台查看','#173177'],

                    ],
                ]);
            } catch (\Throwable $th) {
                
            }
        }
        
    }


    //  _____      __  __         ____ __  __ ____  
    // |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
    //   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
    //   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
    //   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2021/07/17
    //      |_|                                         | TpMeCMS   模板消息结束

  

    public function test($openid='o2n8_6fh0TfnF3pngecOLdW1k7lU')
    {
         $s = microtime(true);
         for ($i=0; $i < 10; $i++) { 
             $data = $this->send_ltd_ask_order($openid,'Bianhao',date('Y-m-d H:i:s'));//用户openid，订单编号,时间
             //调用方式 
            
         }
         // $this->request_asynchronous("/api/template/ltd_ask_order?id=1",'GET');
         
         echo  microtime(true)-$s;
         // halt(1);
         $app = $this->get_wx_gzh_app();
         halt($data);
         $next_openid = null;
         $ci = 0;
         // halt($users);
         $t= true;
      
         //     $users = $app->user->list($next_openid);
         //     // if($users['total']<130 || empty($users)){$t =false;}
         //     // $next_openid = $users['next_openid'];
     
         //     foreach($users['data']['openid'] as $key=>$openId){
         //         $user = $app->user->get($openId);
         //         // halt($users);
         //         if(!empty($user['openid']) && !empty($user['unionid'])){
         //             $up_data['wx_openid'] = $user['openid'];//微信openid
         //             $up_data['nickname'] = $user['nickname'];//微信nickname
         //             $up_data['headurl'] = $up_data['headimage'] = $user['headimgurl'];//微信headimgurl
         //             $t_user = Db::name('shop_user')->where('unionid',$user['unionid'])->find();
         //             if($t_user){
         //                 // halt($t_user);
         //             }
         //             $res = Db::name('shop_user')->where('unionid',$user['unionid'])->update($up_data);
         //             if($res){
         //                 $ci++;
         //             }
         //             unset($up_data);
                     
         //         }
         //         unset($user);
                 
         //     }
       
         // echo $ci;
         
         // if(!$storesid){
         //     $this->is_uid();
         //     $stores = Db::name('shop_stores')->where('uid',$this->uid)->find();
         //     $storesid = $stores['id'];
         // }
         // $list = Db::name('shop_kaizhi')->where('storesid',$storesid)->field(['*,FROM_UNIXTIME(createtime,"%Y-%m-%d %H:%i") as date'])->select();
         // $this->success('ok',$list);
         
         // halt($app);
         // $data = $app->template_message->send([
         //     'touser' => 'o2n8_6fh0TfnF3pngecOLdW1k7lU',
         //     'template_id' => 'TYiVKr1NKHUn6klWdFQ2PKE13jVEcx9FDj3ynShgxTc',
         //     'url' => 'https://meiye.hnbjx.net.cn/',
         //     'miniprogram' => [
         //             'appid' => Config('site.app_id'),
         //             'pagepath' => 'pages/u_syr_yyorder/u_syr_yyorder',
         //     ],
         //     'data' => [
         //         'first' =>['您好，您有新的预约，请及时查看','#173177'],
         //         'keyword1' =>['xiaohe_addr_mobile','#173177'],
         //         'keyword2' =>['ytime','#173177'],
         //         'keyword3' =>['service','#173177'],
         //         'remark' =>['请尽快登入小程序查看','#173177'],
 
         //     ],
         // ]);
 
 
         $data = $app->template_message->send([
             'touser' => $openid,
             'template_id' => '_es-MdHZUO-voldjdevPADHj28JQ_t9bPzxowh_M8LM',
             'url' => 'https://he4966.cn/',
             'miniprogram' => [
                     'appid' => Config('site.app_id'),
                     'pagepath' => 'pages/u_syr_yyorder/u_syr_yyorder',
             ],
             'data' => [
                 'first' =>['您好，您有新的订单信息，请及时查看','#173177'],
                 'keyword1' =>['addr_mobile','#173177'],
                 'keyword2' =>['ytime','#173177'],
                 'keyword3' =>['service','#173177'],
                 'remark' =>['请尽快登入小程序查看','#173177'],
 
             ],
         ]);
         halt($data);
 
          $accessToken = $app->access_token; // EasyWeChat\Core\AccessToken 实例
         $token = $accessToken->getToken(); // token 字符串
         // $token = $accessToken->getToken(true); // 强制重新从微信服务器获取 token.
         $access_token =$token['access_token'];
         
          $openid = $this->oauth($access_token,$openid);
 
 
 
 
          $data = $app->template_message->send([
             'touser' => $openid,
             'template_id' => 'TYiVKr1NKHUn6klWdFQ2PKE13jVEcx9FDj3ynShgxTc',
             'url' => 'https://meiye.hnbjx.net.cn/',
             'miniprogram' => [
                     'appid' => Config('site.app_id'),
                     'pagepath' => 'pages/u_syr_yyorder/u_syr_yyorder',
             ],
             'data' => [
                 'first' =>['您好，您有新的预约，请及时查看','#173177'],
                 'keyword1' =>['addr_mobile','#173177'],
                 'keyword2' =>['ytime','#173177'],
                 'keyword3' =>['service','#173177'],
                 'remark' =>['请尽快登入小程序查看','#173177'],
 
             ],
         ]);
         halt($data);
 
 
 
         $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";
 
 
 
         $value = '{
             "touser":"'.'o2n8_6fh0TfnF3pngecOLdW1k7lU'.'",
             "template_id":"TYiVKr1NKHUn6klWdFQ2PKE13jVEcx9FDj3ynShgxTc",
             "miniprogram":{
              "appid":"wx0fc161ddec2fa1f9",
              "pagepath":"pages/u_syr_yyorder/u_syr_yyorder"
             },
             "topcolor":"#FF0000",
             "data":{
                 "first": {
                     "value":"您好，您有新的预约，请及时查看",
                     "color":"#173177"
                 },
                 "keyword1":{
                     "value":"地址手机号",
                     "color":"#173177"
                 },
                 "keyword2":{
                     "value":"时间",
                     "color":"#173177"
                 },
                 "keyword3":{
                     "value":"服务",
                     "color":"#173177"
                 },
                 "remark":{
                     "value":"请尽快登入小程序查看",
                     "color":"#173177"
                 }
             }
         }';
         $http = new Http;
         halt($http->post($url,$value));
 
    }

    


    public function get_openid()
    {
        $app = $this->get_wx_gzh_app();
        $oauth = $app->oauth;

        // $oauth = $app->oauth;
            // 未登录
        if (empty(Session::get('wechat_user'))) {
            // halt('没有https://he4966.cn/api/template/test_send_ltd_ask_order');
            $url = $this->request->domain().'/api/template/login';
            Session::set('target_url','user/profile');
        
            return $oauth->redirect($url);
            // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用
            // $oauth->redirect()->send();
        }else{
            var_dump('_SESSIONwechat_user');
            halt(Session::get('wechat_user'));
        }
        
        // 已经登录过
        $user = Session::get('wechat_user');
        return $user;
        // halt($user);
    }

    public function index()
    {
            $app = $this->get_wx_gzh_app();
            $oauth = $app->oauth;

            $oauth = $app->oauth;
        // 未登录
        if (empty($_SESSION['wechat_user'])) {
                $url = $this->request->domain().'/api/template/login';
                $_SESSION['target_url'] = 'user/profile';
            
                return $oauth->redirect($url);
                // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用
                // $oauth->redirect()->send();
            }
            
            // 已经登录过
            $user = $_SESSION['wechat_user'];
            // halt($user);
    }



    public function oauth($token,$openid){
        // $wx_user=M('ShopWxUser');
        // $conf = M('WechatConf')->where("id=10000")->find();
        // $token=$this->access_token();
        $url="https://api.weixin.qq.com/cgi-bin/user/get?access_token={$token}&next_openid=";
        $result = file_get_contents($url);
        $json = json_decode($result,true);
        // halt($json);
        $arr=$json['data'];
        $open_arr=$arr['openid'];

        

            
        foreach($open_arr as $k=>$v){
            // $openid=$v;
            // halt($v);
            return $v;
            $url2="https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$openid}&lang=zh_CN";
            $result2 = file_get_contents($url2);
            $json2 = json_decode($result2,true);
            print_r($json2);
            // $is=$wx_user->where("openid='{$json2[openid]}'")->getField('id');
            // if(!$is){
            //     $ww=array();
            //     $ww['openid']=$json2['openid'];
            //     $ww['unionid']=$json2['unionid'];
            //     $ww['nickname']=$json2['nickname'];
            //     $ww['dateline']=time();
            //     halt($ww);
            //     // $wx_user->add($ww);
            // }
        }
    }


    /* 
    * @Description: 公众号测试登录
    * @return: 
    */     
    public function login()
    {
            $url = $this->request->domain().'/api/template/code';
            $app = $this->get_wx_gzh_app();
            $response = $app->oauth->scopes(['snsapi_userinfo'])->redirect($url);
            return $response;
            // halt($response);
    }

    /* 
    * @Description: 公众号获取code
    * @return: 
    */   
    public function code()
    {
            $data = $this->request->param();
            $app = $this->get_wx_gzh_app();
            $oauth = $app->oauth;
            $user = $oauth->user();

            // halt($user);
            Session::set('wechat_user',$user->original);
            return $user->original;
    }
    



}